<?php
/**
* goods.php
*
* Create on 2017-2-17
* Create by TT
*/
namespace haibao\cms\data\newproduct;

class Goods extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\newproduct\Goods');
	}
	
	public function getImageIdByGoodsId($goodsId){
	    if(is_array($goodsId)){
	        $str = preg_replace('/(\d+)/', '%s', implode(',', $goodsId));
	        $sql = 'select GoodsId,ImageId from GoodsImage where IsCover = 1 and GoodsId in (' . $str . ')';
	        $result = $this->query($sql,$goodsId);
	        $imageIds = array();
	        while($row = $result->fetch_assoc()){
	            $imageIds[$row['GoodsId']] = $row['ImageId'];
	        }
	        return $imageIds;
	    }else{
	        $sql = 'select ImageId from GoodsImage where IsCover = 1 and GoodsId = %s';
	        return $this->query($sql,array($goodsId))->fetch_assoc();
	    }
	    
	}
	
	public function addGoodsScore($userId,$goodsId,$score){
	    $sql = 'insert into GoodsScore (UserId,GoodsId,Score,CreateTime) values(%s,%s,%s,%s)';
	    $this->query($sql,array($userId,$goodsId,$score,date('Y-m-d H:i:s')));
	    return $userId;
	}
	
	public function getUserGoodsScore($goodsId,$userId){
	    $sql = 'select Score from GoodsScore where GoodsId = %s and UserId=%s';
	    return $this->query($sql,array($goodsId,$userId))->fetch_assoc();
	}
	
	public function getUseCount($goodsId){
		$sql = 'select UseCount from GoodsStatistic where GoodsId = %s';
		return $this->query($sql,array($goodsId))->fetch_assoc();
	}
	
	public function addUseCount($goodsId){
		$sql = 'update GoodsStatistic set UseCount=UseCount+1 where GoodsId = %s';
		$this->query($sql,array($goodsId));
	}

    public function addGoodsStatistic($goodsId){
	    $useCount = rand(15,50);
        $sql = 'INSERT INTO GoodsStatistic (GoodsId,UseCount) VALUES ('.$goodsId.','.$useCount.')';
        $this->query($sql,array($goodsId));
    }
	
    public function getGoodsScore($goodsId){
        $sql = 'select Score from GoodsScore where GoodsId = %s';
        $result = $this->query($sql,array($goodsId));
        $scoreList = array();
        while($row = $result->fetch_assoc()){
            $scoreList[] = $row['Score'];
        }
        return $scoreList;
    }

	
	public function getNewProductByBrandId($brandId){
	    $sql = 'select BrandId,ProductId from ProductBrandGroup_New where BrandId = %s order by Id desc limit 5 ';
	    $productResult = $this->query($sql,array($brandId));
	    $productInfo = array();
	    while($row = $productResult->fetch_assoc()){
	        $productInfo[] = $row['ProductId'];
	    }
	    return $productInfo;
	}
	
	public function getTryOutByProductId($goodsId,$isOnTry = true){
	    $temp = '';
	    if($isOnTry){
	        $temp = 'and ApplyStartTime <= %s and ApplyEndTime >= %s';
	    }else{
	        $temp = 'and ApplyEndTime < %s';
	    }
	    $date = date('Y-m-d H:i:s');
	    $sql = 'select Id,Title,Amount,Specifications,Price,PicId,ApplyEndTime from TryProduct where ProductModelId = %s and Status = 1 '.$temp.' order By Id desc';
	    if($temp){
	        return $this->query($sql,array($goodsId,$date,$date))->fetch_assoc();
	    }else{
	        return $this->query($sql,array($goodsId,$date))->fetch_assoc();
	    }
	    
	}
	
	public function getCategoryNameById($categoryId){
	   $categoryInfo = array();
       if(is_array($categoryId)){
           $str = preg_replace('/(\d+)/', '%s', implode(',', $categoryId));
           $sql = 'select Id,CategoryName from ProductCategoryDefine_New where Id in (' . $str . ')';
           $categoryResult = $this->query($sql,$categoryId);
           while($row = $categoryResult->fetch_assoc()){
               $categoryInfo[$row['Id']] = $row['CategoryName'];
           }
           return $categoryInfo;
       }else{
           $sql = 'select Id,CategoryName from ProductCategoryDefine_New where Id = %s';
           $categoryResult = $this->query($sql,array($categoryId))->fetch_assoc();
           if(isset($categoryResult['Id']) && isset($categoryResult['CategoryName'])){
               $categoryInfo[$categoryResult['Id']] = $categoryResult['CategoryName'];
           }
       }
	   
	   return $categoryInfo;
	}
	
	public function getGoodsPropertyById($goodsId){
	    $sql = 'select a.PropertyId,a.DataValue,a.LinkageVal,b.Name from GoodsProperty as a left join ProductProperty as b on a.PropertyId = b.Id where a.GoodsId = %s';
	    $valueResult = $this->query($sql,array($goodsId));
	    $propertyValue = array();
	    while($row = $valueResult->fetch_assoc()){
	        $propertyValue[] = $row;
	    }
        return $propertyValue;
	}

	public function getGoodsProperyByIds($goodsIds){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $goodsIds));
        $sql = 'select a.GoodsId,a.PropertyId,a.DataValue,a.LinkageVal,b.Name from GoodsProperty as a left join ProductProperty as b on a.PropertyId = b.Id where a.GoodsId in ('.$str.')';
        $valueResult = $this->query($sql,$goodsIds);
        $propertyValue = array();
        while($row = $valueResult->fetch_assoc()){
            $propertyValue[] = $row;
        }
        return $propertyValue;
    }
	
	
	public function batchUpdateProduct($ids,$arrSet,$modelPropertyModes){
	
		self::beginTranscation();
		try{
			$goodsFilter = new \haibao\cms\model\filter\newproduct\Goods();
			$goodsFilter->where(\haibao\cms\model\filter\newproduct\Goods::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_IN, $ids);
			self::update($arrSet, $goodsFilter);
				
			$this->updateBrandUpdateTime($ids[0]);
				
			if($modelPropertyModes){
				//先删除单品模型属性值
				$str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
				$sql = 'delete from GoodsProperty where GoodsId in (' . $str . ')';
				$this->query($sql,$ids);
				//再添加
				$arrValues = array();
				$arrSql = array();
				foreach($modelPropertyModes as $model){
					array_push($arrSql,'(%s,%s,%s,%s)');
					array_push($arrValues,$model->PropertyId);
					array_push($arrValues,$model->GoodsId);
					array_push($arrValues,$model->DataValue);
					array_push($arrValues,$model->LinkageVal);
				}
				$sql = "insert into GoodsProperty (PropertyId, GoodsId,DataValue,LinkageVal) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
			}
				
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function updateProduct($id,$arrSet,$propertyModels,$picId = 0){
		self::beginTranscation();
		try{
			parent::updateById($id, $arrSet);
			if($picId){
				$sql = 'update GoodsImage set ImageId=%s where GoodsId=%s and IsCover=1';
				$this->query($sql,array($picId,$id));
			}
			$this->updateBrandUpdateTime($id);
				
			if($propertyModels){
				//先删除单品模型属性值
				$sql = 'delete from GoodsProperty where GoodsId=%s';
				$this->query($sql,array($id));
				//再添加
				$arrValues = array();
				$arrSql = array();
				foreach($propertyModels as $model){
					array_push($arrSql,'(%s,%s,%s,%s)');
					array_push($arrValues,$model->PropertyId);
					array_push($arrValues,$model->GoodsId);
					array_push($arrValues,$model->DataValue);
					array_push($arrValues,$model->LinkageVal);
				}
				$sql = "insert into GoodsProperty (PropertyId, GoodsId,DataValue,LinkageVal) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
			}
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function updateStatusByProductId($productId,$status = \haibao\cms\model\data\newproduct\Product::STATUS_ENABLE){
		$sql = 'update Goods set Status=%s where ProductId=%s';
		$this->query($sql,array($status,$productId));
	
		//TT addtime 2015.11.26
		//修改品牌库某品牌记录的修改日期
		$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where Id in (SELECT BrandId from ProductBrandGroup_New where ProductId=%s)";
		$this->query($sql,array($productId));
	}
	
	public function updateStatusById($id,$status = \haibao\cms\model\data\product::STATUS_ENABLE){
		$sql = 'update Goods set Status=%s where Id=%s';
		$this->query($sql,array($status,$id));
	
		$this->updateBrandUpdateTime($id);
	}

	public function getStatisticByGoodsId($goodsId){
        $sql = 'select * from GoodsStatistic where GoodsId = %s limit 1';
        return $this->query($sql,array($goodsId))->fetch_assoc();
    }

    public function updateCommentNum($goodsId,$num = 1,$isSub=false){
        if ($isSub){
            $sql = 'update GoodsStatistic set CommentNum=CommentNum+'.$num.' where GoodsId=%s';
        }else {
            $sql = 'update GoodsStatistic set CommentNum=CommentNum-'.$num.' where GoodsId=%s';
        }
        $this->query($sql,array($goodsId));
    }

    public function getGoodsInfoByIds($idStr){
        $sql = "SELECT
				a.Id,
				a.Name,
				b.FileName,
				bg.BrandId
		   FROM Goods AS a
			LEFT JOIN GoodsImage as gi on gi.GoodsId = a.Id
			LEFT JOIN ImageLibrary AS b ON gi.ImageId = b.Id
			LEFT JOIN ProductBrandGroup_New as bg on bg.ProductId = a.ProductId
			WHERE
				a.Id IN ($idStr) and gi.IsCover = 1";
        $productResult = $this->query($sql);
        $productInfo = array();
        while($row = $productResult->fetch_assoc()){
            $productInfo[$row['Id']] = $row;
        }
        return $productInfo;
    }

	//TT addtime 2015.11.26
	//修改品牌库某品牌记录的修改日期
	private function updateBrandUpdateTime($goodsId){
		$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where Id in (SELECT BrandId from ProductBrandGroup_New where ProductId in (SELECT ProductId from Goods where id=%s))";
		$this->query ($sql, array($goodsId));
	}
	public function getProductBrandInfo($property){
	    $sql="SELECT p.BrandId,bp.Property,b.NameCN,b.NameEN,b.PinyinCN,b.PinyinEN 
            FROM ProductBrandGroup_New p
            LEFT JOIN BrandProperty bp ON p.BrandId=bp.BrandId
            LEFT JOIN Brand b ON bp.BrandId=b.Id AND b.`Status`= 1
            WHERE   b.NameCN <>'' AND bp.Property=".$property."
            GROUP BY p.BrandId
            ORDER BY p.BrandId";
	    $result = $this->query($sql);
	    $dataList = array();
	    while ($row = $result->fetch_assoc()){
	        if($result->getData('Property')){
	            $dataList[$result->getData('Property')][] = $row;
	        }
	    }
	    return $dataList;
	}

	public function getBrandPropertyId($brandId){
	    $sql="SELECT * FROM BrandProperty WHERE BrandId=%s LIMIT 1";
	    return $this->query($sql,array($brandId))->fetch_assoc();
	}
	
	public function getProductPorperyByCategoryIds($allCategoryArr){
	    $sql = "SELECT a.ProductId,a.CategoryId,b.PropertyId,b.PropertyName,b.DefaultValue FROM ProductCategoryRelation a
                LEFT JOIN ProductPropertyRelation b ON a.ProductId=b.ProductId AND b.DataType=2
                WHERE a.CategoryId IN (".implode(',', $allCategoryArr).")";
	    $result = $this->query($sql);
	    $dataList = array();
	    while ($row = $result->fetch_assoc()){
	        array_push($dataList, $row);
	    }
	    return $dataList;
	}
}